﻿using SportsPlatform.Consts;
using SportsPlatform.Dto.SportBusiness.Information;
using SportsPlatform.SportBusiness.ISportBusiness;
using SportsPlatform.Model.SportBusiness;
using SportsPlatform.Base;
using SportsPlatform.PermissionManagement.PermissionManagement;
using SportsPlatform.Query.SportBusiness.Information;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Abp.Extensions;
using Abp.Application.Services;
using Abp.Domain.Repositories;
using SportsPlatform.Model.PermissionManagement;
using SportsPlatform.Helpers;
using SportsPlatform.Dto.SportBusiness.GetPaymentOrderInfo;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
using static iTextSharp.text.pdf.AcroFields;
using SqlSugar.Extensions;
using NPOI.SS.Formula.Functions;
using MySqlX.XDevAPI.Common;
using Abp.Collections.Extensions;
using Npgsql.NameTranslation;
using NPOI.Util.ArrayExtensions;
using Microsoft.AspNetCore.Http;
using SportsPlatform.Global;
using SqlSugar;

namespace SportsPlatform.SportBusiness.SportBusiness
{
    /// <summary>
    /// 资讯管理服务
    /// </summary>
    [RemoteService(false)]
    public class NewsService : SportsPlatformAppServiceBase, INewsService
    {
        private readonly IRepository<UserInfo, Guid> _userRepository;
        private readonly IRepository<Category, Guid> _categoryRepository;
        private readonly IRepository<Information, Guid> _repository;
        private readonly IRepository<CategoryNews, Guid> _categoryNewsRepository;
        private readonly IRepository<CompanyInfo, Guid> _companyRepository;
        public NewsService(IRepository<Information, Guid> repository,
            IRepository<UserInfo, Guid> userinfoRepository, IRepository<Category, Guid> categoryRepository,
            IRepository<CategoryNews, Guid> categoryNews, IRepository<CompanyInfo, Guid> companyRepository
            , IHttpContextAccessor context) : base(context)
        {
            _userRepository = userinfoRepository;
            _categoryRepository = categoryRepository;
            _repository = repository;
            _categoryNewsRepository = categoryNews;
            _companyRepository = companyRepository;
        }

        /// <summary>
        /// 获取分页后的资讯信息
        /// </summary>
        /// <param name="pageQuery">查询条件参数</param>
        /// <returns></returns>
        public async Task<PagePagingDto<InformationDto>> GetPagePagingDto(GetInformationQuery pageQuery)
        {
            PagePagingDto<InformationDto> result = new PagePagingDto<InformationDto>();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                var dto = (await _repository.GetAllListAsync(i => i.IsDeleted == false))
                    .WhereIF(!pageQuery.Keywords.IsNullOrWhiteSpace(), i => i.ArticleTitle.Contains(pageQuery.Keywords))
                    .WhereIF(pageQuery.CompanyId != null, info => info.CompanyId == pageQuery.CompanyId)
                    .WhereIF(pageQuery.CompanyId == null && token.CompanyId != null, info => info.CompanyId == token.CompanyId)
                    .WhereIF(pageQuery.CompanyId == null && token.CompanyId == null && pageQuery.IsPlatform == true, info => info.CompanyId == null || info.CompanyId == Guid.Empty)
                    .ToList();
                List<Category> categories = new List<Category>();
                List<InformationDto> informationDtos = new List<InformationDto>();

                //关键字条件查询
                var ids = new List<Guid>();
                var news = (await _categoryNewsRepository.GetAllListAsync(a => a.IsDeleted == false))
                    .WhereIF(pageQuery.CompanyId != null, info => info.CompanyId == pageQuery.CompanyId)
                    .WhereIF(pageQuery.CompanyId == null && token.CompanyId != null, info => info.CompanyId == token.CompanyId)
                    .WhereIF(pageQuery.CompanyId == null && token.CompanyId == null && pageQuery.IsPlatform == true, info => info.CompanyId == null || info.CompanyId == Guid.Empty)
                    .ToList();
                //所属分类条件查询
                if (!pageQuery.CategoryIds.IsNullAndEmpty() && pageQuery.CategoryIds.Length > 0 && (!pageQuery.CategoryIds.Contains("")))
                {
                    foreach (var pid in pageQuery.CategoryIds)
                    {
                        if (!pid.IsNullAndEmpty())
                        {
                            var newss = news.Where(a => a.CategoryId == Guid.Parse(pid)).ToList();
                            if (newss.Count > 0)
                            {
                                foreach (var n in newss)
                                {
                                    if (!ids.Contains(n.NewsId))
                                    {
                                        ids.Add(n.NewsId);
                                    }
                                }
                            }
                        }
                    }
                    //有条件，确没有查到匹配的，说明没有数据
                    if (ids.Count == 0)
                    {
                        result.Code = HttpResultCode.SqlError;
                        result.IsSuccess = false;
                        result.Message = "未查询到数据";
                        return result;
                    }
                }
                //将两个查询条件合并查询，并分页
                dto = dto.WhereIf(ids.Count > 0, a => ids.Contains(a.Id)).ToList();
                var info = dto.Skip((pageQuery.PageIndex - 1) * pageQuery.PageSize).Take(pageQuery.PageSize).ToList();

                if (info.Count > 0)
                {
                    foreach (var item in info)
                    {
                        var user = await _userRepository.GetAsync(item.CreateUserId);

                        var informationDto = new InformationDto
                        {
                            ArticleContent = item.ArticleContent,
                            ArticleTitle = item.ArticleTitle,
                            Cover = item.Cover,
                            CreateTime = item.CreateTime.ToString("yyyy-MM-dd"),
                            Id = item.Id,
                            IsEnable = item.IsEnable,
                            Order = item.Sort,
                            ReadingCount = item.ReadingCount,
                            ShareSummary = item.ShareSummary,
                            CreateUserName = user == null ? "" : user.UserName,
                            CompanyName = (item.CompanyId != null && item.CompanyId != Guid.Empty) ? _companyRepository.FirstOrDefault(info => info.Id == item.CompanyId).CompanyName : ""
                        };

                        var queryNews = await _categoryNewsRepository.GetAllListAsync(i => i.IsDeleted == false && i.NewsId == item.Id);

                        foreach (var n in queryNews)
                        {
                            var category = await _categoryRepository.GetAsync(n.CategoryId);
                            if (!category.IsNullAndEmpty())
                            {
                                categories.Add(category);
                            }
                        }
                        categories.ForEach(i =>
                        {
                            informationDto.CategoryName += i.Name + ",";
                        });
                        informationDto.CategoryName = informationDto.CategoryName.Substring(0, informationDto.CategoryName.Length - 1);
                        informationDtos.Add(informationDto);
                        categories.Clear();
                    }
                    result.TotalCount = dto.Count();
                    result.Code = HttpResultCode.Success;
                    result.IsSuccess = true;
                    result.Message = "查询成功";
                    result.Data = informationDtos.OrderByDescending(i => i.CreateTime).ToList();
                    return result;
                }
                else
                {
                    result.Code = HttpResultCode.SqlError;
                    result.IsSuccess = false;
                    result.Message = "未查询到数据";
                }
            }
            catch (Exception e)
            {
                result.Code = HttpResultCode.Error;
                result.IsSuccess = false;
                result.Message = e.Message;
            }
            return result;
        }

        /// <summary>
        /// 开始添加资讯信息
        /// </summary>
        /// <param name="addInformationQuery">传入参数</param>
        /// <returns></returns>
        public async Task<BaseResultDto> AddStart(AddInformationQuery addInformationQuery)
        {
            BaseResultDto resultDto = new BaseResultDto();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                var res = ObjectMapper.Map<Information>(addInformationQuery);

                //var user = await _userRepository.GetAsync(userid);

                //if (user.IsNullAndEmpty())
                //{
                //    resultDto.Code = HttpResultCode.Success;
                //    resultDto.IsSuccess = true;
                //    resultDto.Message = "当前用户不存在";
                //    return resultDto;
                //}
                res.CreateTime = DateTime.Now;
                res.CreateUserId = token.Id;
                res.CompanyId = token.CompanyId;

                var information = await _repository.InsertAsync(res);
                if (information.IsNullAndEmpty())
                {
                    resultDto.Code = HttpResultCode.NotData;
                    resultDto.IsSuccess = false;
                    resultDto.Message = "添加失败";
                    return resultDto;
                }
                if (!addInformationQuery.CategoryIds.IsNullAndEmpty())
                {
                    foreach (var Id in addInformationQuery.CategoryIds)
                    {
                        if (!string.IsNullOrEmpty(Id))
                        {
                            var category = await _categoryRepository.GetAsync(new Guid(Id));
                            if (category.IsNullAndEmpty())
                            {
                                resultDto.Code = HttpResultCode.Fail;
                                resultDto.IsSuccess = false;
                                resultDto.Message = "选择分类不存在";
                                return resultDto;
                            }
                            await _categoryNewsRepository.InsertAsync(new CategoryNews
                            {
                                CategoryId = category.Id,
                                CreateTime = DateTime.Now,
                                CreateUserId = token.Id,
                                CompanyId = token.CompanyId,
                                NewsId = information.Id

                            });
                        }
                    }
                    resultDto.Code = HttpResultCode.Success;
                    resultDto.IsSuccess = true;
                    resultDto.Message = "添加成功";
                    return resultDto;
                }
                else
                {
                    resultDto.Code = HttpResultCode.NotData;
                    resultDto.Message = "没有选择分类";
                    return resultDto;
                }
            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.Message;
            }
            return resultDto;
        }

        /// <summary>
        /// 开始更新资讯信息
        /// </summary>
        /// <param name="updateInformationQuery">传入参数</param>
        /// <returns></returns>
        public async Task<BaseResultDto> UpdateStart(UpdateInformationQuery updateInformationQuery)
        {
            BaseResultDto resultDto = new BaseResultDto();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                if (token.IsNullAndEmpty())
                {
                    resultDto.Code = HttpResultCode.Fail;
                    resultDto.IsSuccess = false;
                    resultDto.Message = "当前用户不存在";
                    return resultDto;
                }
                var information = await _repository.GetAsync(updateInformationQuery.Id);
                if (information.IsNullAndEmpty())
                {
                    resultDto.Code = HttpResultCode.Fail;
                    resultDto.IsSuccess = false;
                    resultDto.Message = "当前资讯不存在";
                    return resultDto;
                }

                var cns = await _categoryNewsRepository.GetAllListAsync(cn => cn.NewsId == information.Id && cn.IsDeleted == false);
                if (cns.Count > 0)
                {
                    foreach (var item in cns)
                    {
                        item.IsDeleted = true;
                        item.DeleteTime = DateTime.Now;
                        item.DeleteUserId = token.Id;
                        await _categoryNewsRepository.UpdateAsync(item);
                    }
                }

                foreach (var item in updateInformationQuery.CategoryIds)
                {
                    var category = await _categoryRepository.GetAsync(new Guid(item));
                    if (category.IsNullAndEmpty())
                    {
                        resultDto.Code = HttpResultCode.Fail;
                        resultDto.IsSuccess = false;
                        resultDto.Message = "当前资讯不存在";
                        return resultDto;
                    }
                    await _categoryNewsRepository.InsertAsync(new CategoryNews
                    {
                        CategoryId = category.Id,
                        NewsId = information.Id,
                        CreateTime = DateTime.Now,
                        CreateUserId = token.Id,
                        CompanyId = information.CompanyId
                    });
                }

                information.UpdateUserId = token.Id;
                information.UpdateTime = DateTime.Now;
                information.ShareSummary = updateInformationQuery.ShareSummary;
                information.IsEnable = updateInformationQuery.IsEnable;
                information.Cover = updateInformationQuery.Cover;
                information.ArticleContent = updateInformationQuery.ArticleContent;
                information.ArticleTitle = updateInformationQuery.ArticleTitle;
                information.Sort = updateInformationQuery.Sort;
                var updateinformation = await _repository.UpdateAsync(information);

                resultDto.Code = !updateinformation.IsNullAndEmpty() ? HttpResultCode.Success : HttpResultCode.SqlError;
                resultDto.IsSuccess = !updateinformation.IsNullAndEmpty();
                resultDto.Message = !updateinformation.IsNullAndEmpty() ? "更新成功" : "更新失败";
            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.Message;
            }
            return resultDto;
        }

        /// <summary>
        /// 开始删除资讯信息
        /// </summary>
        /// <param name="deleteInformationQuery">传入参数</param>
        /// <returns></returns>
        public async Task<BaseResultDto> DeleteStart(DeleteInformationQuery deleteInformationQuery)
        {
            BaseResultDto resultDto = new BaseResultDto();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                if (token.IsNullAndEmpty())
                {
                    resultDto.Code = HttpResultCode.Fail;
                    resultDto.IsSuccess = false;
                    resultDto.Message = "当前用户不存在";
                    return resultDto;
                }
                var information = await _repository.GetAsync(deleteInformationQuery.Id);
                if (information.IsNullAndEmpty())
                {
                    resultDto.Code = HttpResultCode.Fail;
                    resultDto.IsSuccess = false;
                    resultDto.Message = "当前资讯不存在";
                    return resultDto;
                }
                information.IsDeleted = true;
                information.DeleteTime = DateTime.Now;
                information.DeleteUserId = token.Id;
                var updateinformation = await _repository.UpdateAsync(information);
                var newsCategorys = await _categoryNewsRepository.GetAllListAsync(i => i.NewsId == information.Id && i.IsDeleted == false);
                foreach (var item in newsCategorys)
                {
                    item.IsDeleted = true;
                    item.DeleteTime = DateTime.Now;
                    item.DeleteUserId = token.Id;
                    await _categoryNewsRepository.UpdateAsync(item);
                }
                resultDto.Code = !updateinformation.IsNullAndEmpty() ? HttpResultCode.Success : HttpResultCode.SqlError;
                resultDto.IsSuccess = !updateinformation.IsNullAndEmpty() ? true : false;
                resultDto.Message = !updateinformation.IsNullAndEmpty() ? "删除成功" : "删除失败";
            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.Message = e.Message;
                resultDto.IsSuccess = false;
            }
            return resultDto;
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="updateSateQuery">传入参数</param>
        /// <returns></returns>
        public async Task<BaseResultDto> UpdateStateStart(UpdateNewsSateQuery updateSateQuery)
        {
            BaseResultDto resultDto = new BaseResultDto();
            try
            {
                var user = await _userRepository.GetAsync(updateSateQuery.UpdateUserId);

                if (user.IsNullAndEmpty())
                {
                    resultDto.Code = HttpResultCode.Fail;
                    resultDto.IsSuccess = false;
                    resultDto.Message = "当前用户不存在";
                    return resultDto;
                }
                var information = await _repository.GetAsync(updateSateQuery.Id);
                if (information.IsNullAndEmpty())
                {
                    resultDto.Code = HttpResultCode.Fail;
                    resultDto.IsSuccess = false;
                    resultDto.Message = "当前资讯不存在";
                    return resultDto;
                }
                information.IsEnable = updateSateQuery.IsEnable;
                information.UpdateUserId = updateSateQuery.UpdateUserId;
                information.UpdateTime = DateTime.Now;
                var updateinformation = await _repository.UpdateAsync(information);

                resultDto.Code = !updateinformation.IsNullAndEmpty() ? HttpResultCode.Success : HttpResultCode.SqlError;
                resultDto.IsSuccess = !updateinformation.IsNullAndEmpty() ? true : false;
                resultDto.Message = !updateinformation.IsNullAndEmpty() ? "更新成功" : "更新失败";
            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.Message;
            }
            return resultDto;
        }

        /// <summary>
        /// 通过标识获取对应资讯，并进行更新
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ResultDto<UpdateInformationQuery>> GetById(Guid id)
        {
            var resultDto = new ResultDto<UpdateInformationQuery>();
            try
            {
                var res = await _repository.GetAsync(id);

                if (!res.IsNullAndEmpty())
                {
                    var news = ObjectMapper.Map<UpdateInformationQuery>(res);
                    var cns = await _categoryNewsRepository.GetAllListAsync(i => i.NewsId == res.Id && i.IsDeleted == false);
                    List<Category> categories = new List<Category>();
                    if (cns.Count > 0)
                    {
                        foreach (var item in cns)
                        {
                            var category = await _categoryRepository.GetAsync(item.CategoryId);
                            if (category.IsNullAndEmpty())
                            {
                                resultDto.Code = HttpResultCode.NotData;
                                resultDto.IsSuccess = false;
                                resultDto.Message = "不存在该分类";
                                return resultDto;
                            }
                            categories.Add(category);
                        }
                    }
                    if (categories.Count > 0)
                    {
                        List<string> strings = new List<string>();
                        foreach (var item in categories)
                        {
                            strings.Add(item.Id.ToString());
                            news.CategoryIds = strings.ToArray();
                        }
                    }
                    resultDto.Code = HttpResultCode.Success;
                    resultDto.IsSuccess = true;
                    resultDto.Message = "查询成功";
                    resultDto.Data = news;
                }
                else
                {
                    resultDto.Code = HttpResultCode.NotData;
                    resultDto.IsSuccess = false;
                    resultDto.Message = "未查询到数据";
                }

            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.Message.ToString();
            }
            return resultDto;
        }
    }
}
